Interface பொருள்
Interface வகுப்பு Node.js இல் உள்ள readline தொகுதியின் ஒரு பகுதியாகும். இது Readable ஸ்ட்ரீமில் இருந்து (process.stdin போன்ற) தரவை ஒரு நேரத்தில் ஒரு வரியாக வாசிக்க ஒரு வழியை வழங்குகிறது. இது கட்டளை வரி இடைமுகங்கள் (CLIs) மற்றும் ஊடாடும் கேள்விகளை உருவாக்க பொதுவாகப் பயன்படுத்தப்படுகிறது.
கட்டளை வரி இடைமுகங்கள்
CLI பயன்பாடுகள் மற்றும் கட்டளை கருவிகளை உருவாக்க உதவுகிறது
ஊடாடும் கேள்விகள்
பயனர்களிடமிருந்து உள்ளீட்டைப் பெற ஊடாடும் வழிகளை வழங்குகிறது
ஸ்ட்ரீம் கையாளுதல்
Readable மற்றும் Writable ஸ்ட்ரீம்களுடன் நேரடியாக வேலை செய்கிறது
readline தொகுதியை இறக்குமதி செய்தல்
// Import the readline module
const readline = require('readline');
// Create an Interface instance
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
Interface பண்புகள்
| பண்பு | விளக்கம் |
|---|---|
| rl.line | தற்போது செயலாக்கப்படும் உள்ளீட்டு வரி |
| rl.cursor | தற்போதைய வரியில் கர்சர் நிலை |
| rl.input | பயன்படுத்தப்படும் Readable ஸ்ட்ரீம் |
| rl.output | பயன்படுத்தப்படும் Writable ஸ்ட்ரீம் |
| rl.terminal | ஸ்ட்ரீம் TTY போலவே நடத்தப்பட வேண்டுமா மற்றும் ANSI/VT100 எஸ்கேப் குறியீடுகள் எழுதப்பட வேண்டுமா என்பதைக் குறிக்கும் பூலியன் |
| rl.history | வரலாறு பஃபர் வழங்கப்பட்டிருந்தால். Promise-அடிப்படையிலான API பயன்படுத்தும் போது இது கிடைக்காது |
Interface முறைகள்
| முறை | விளக்கம் |
|---|---|
| rl.question(query, callback) | கேள்வியைப் பயனருக்குக் காட்டி அவர்களின் உள்ளீட்டிற்காகக் காத்திருக்கிறது. அவர்கள் வழங்கியவுடன், பயனரின் உள்ளீட்டை அதன் முதல் வாதமாகக் கொண்டு callback ஐ அழைக்கிறது |
| rl.close() | Interface நிகழ்வை மூடுகிறது, உள்ளீடு மற்றும் வெளியீட்டு ஸ்ட்ரீம்களின் கட்டுப்பாட்டை விட்டுக்கொடுக்கிறது |
| rl.pause() | readline உள்ளீட்டு ஸ்ட்ரீமை இடைநிறுத்துகிறது, அது பின்னர் மீண்டும் தொடங்க அனுமதிக்கிறது |
| rl.resume() | readline உள்ளீட்டு ஸ்ட்ரீமை மீண்டும் தொடங்குகிறது |
| rl.write(data[, key]) | வெளியீட்டு ஸ்ட்ரீமில் தரவை எழுதுகிறது. key வாதம் ctrl அல்லது meta போன்ற சிறப்பு எழுத்துகளைக் கொண்ட ஒரு பொருளாக இருக்கலாம் |
| rl.prompt([preserveCursor]) | பயனர் உள்ளீடு செய்வதற்கான prompt ஐக் காட்டுகிறது. preserveCursor true எனில், கர்சர் நிலை மீட்டமைக்கப்படாது |
| rl.getPrompt() | தற்போதைய prompt சரத்தை வழங்குகிறது |
| rl.setPrompt(prompt) | rl.prompt() அழைக்கப்படும் போது காட்டப்படும் prompt சரத்தை அமைக்கிறது |
Interface நிகழ்வுகள்
| நிகழ்வு | விளக்கம் |
|---|---|
| 'close' | Interface நிகழ்வு மூடப்படும் போது உமிழப்படுகிறது |
| 'line' | பயனர் Enter விசையை அழுத்தி உள்ளீட்டின் ஒரு வரியைச் சமர்ப்பிக்கும் போது உமிழப்படுகிறது |
| 'pause' | உள்ளீட்டு ஸ்ட்ரீம் இடைநிறுத்தப்படும் போது உமிழப்படுகிறது |
| 'resume' | உள்ளீட்டு ஸ்ட்ரீம் மீண்டும் தொடங்கப்படும் போது உமிழப்படுகிறது |
| 'SIGCONT' | முன்பு Ctrl+Z (SIGTSTP) உடன் இடைநிறுத்தப்பட்ட Node.js செயல்முறை மீண்டும் தொடங்கப்படும் போது உமிழப்படுகிறது |
| 'SIGINT' | Ctrl+C அழுத்தப்படும் போது உமிழப்படுகிறது, SIGINT என அறியப்படுகிறது |
| 'SIGTSTP' | Ctrl+Z அழுத்தப்படும் போது உமிழப்படுகிறது, SIGTSTP என அறியப்படுகிறது |
| 'history' | வரலாறு மாறும் போதெல்லாம் உமிழப்படுகிறது |
அடிப்படை பயன்பாடு எடுத்துக்காட்டு
இந்த எடுத்துக்காட்டு ஒரு எளிய கட்டளை வரி prompt உருவாக்க Interface பொருளின் அடிப்படை பயன்பாட்டை நிரூபிக்கிறது:
const readline = require('readline');
// Create interface for reading from stdin and writing to stdout
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
// Ask a question and get the user's input
rl.question('What is your name? ', (name) => {
console.log(`Hello, ${name}!`);
// Ask another question
rl.question('How are you today? ', (response) => {
console.log(`Glad to hear: ${response}`);
// Close the interface
rl.close();
});
});
// Handle the close event
rl.on('close', () => {
console.log('Interface closed. Goodbye!');
});
Promise-அடிப்படையிலான API எடுத்துக்காட்டு
Node.js v17+ readline க்கு promise-அடிப்படையிலான API ஐ வழங்குகிறது:
// For Node.js v17 and above:
const readline = require('readline/promises');
const { stdin: input, stdout: output } = require('process');
async function askQuestions() {
const rl = readline.createInterface({ input, output });
try {
// Ask questions sequentially
const name = await rl.question('What is your name? ');
console.log(`Hello, ${name}!`);
const age = await rl.question('How old are you? ');
console.log(`You are ${age} years old.`);
const location = await rl.question('Where do you live? ');
console.log(`${location} is a nice place!`);
// Summary
console.log('\nSummary:');
console.log(`Name: ${name}`);
console.log(`Age: ${age}`);
console.log(`Location: ${location}`);
} finally {
// Make sure to close the interface
rl.close();
}
}
// Run the async function
askQuestions()
.then(() => console.log('Questions completed!'))
.catch(err => console.error('Error:', err));
கட்டளை வரி இடைமுக எடுத்துக்காட்டு
வரலாறு ஆதரவுடன் ஒரு எளிய கட்டளை வரி இடைமுகத்தை உருவாக்குதல்:
const readline = require('readline');
const fs = require('fs');
const path = require('path');
// History file path
const historyFile = path.join(__dirname, '.command_history');
// Load command history if it exists
let commandHistory = [];
try {
if (fs.existsSync(historyFile)) {
commandHistory = fs.readFileSync(historyFile, 'utf8')
.split('\n')
.filter(cmd => cmd.trim());
}
} catch (err) {
console.error('Error loading history:', err.message);
}
// Create the interface with custom configuration
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
prompt: 'cli> ',
historySize: 100,
history: commandHistory
});
// Available commands
const commands = {
help: () => {
console.log('\nAvailable commands:');
console.log(' help - Show this help message');
console.log(' hello - Say hello');
console.log(' date - Show current date and time');
console.log(' clear - Clear the console');
console.log(' exit - Exit the CLI');
rl.prompt();
},
hello: () => {
console.log('Hello, world!');
rl.prompt();
},
date: () => {
console.log(new Date().toLocaleString());
rl.prompt();
},
clear: () => {
process.stdout.write('\x1Bc');
rl.prompt();
},
exit: () => {
// Save command history to file
try {
fs.writeFileSync(historyFile, rl.history.join('\n'));
console.log(`Command history saved to ${historyFile}`);
} catch (err) {
console.error('Error saving history:', err.message);
}
console.log('Goodbye!');
rl.close();
}
};
// Display welcome message
console.log('Simple CLI Example');
console.log('Type "help" for available commands');
// Display the prompt
rl.prompt();
// Handle input
rl.on('line', (line) => {
const input = line.trim();
if (input === '') {
rl.prompt();
return;
}
const command = input.toLowerCase();
if (commands[command]) {
commands[command]();
} else {
console.log(`Command not found: ${input}`);
console.log('Type "help" for available commands');
rl.prompt();
}
}).on('close', () => {
process.exit(0);
});
// Handle Ctrl+C (SIGINT)
rl.on('SIGINT', () => {
rl.question('Are you sure you want to exit? (y/n) ', (answer) => {
if (answer.toLowerCase() === 'y') {
commands.exit();
} else {
console.log('Operation cancelled');
rl.prompt();
}
});
});
ஊடாடும் கடவுச்சொல் உள்ளீடு
உள்ளிடப்பட்ட எழுத்துகளை மறைக்கும் கடவுச்சொல் உள்ளீட்டை உருவாக்குதல்:
const readline = require('readline');
// Create the interface
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
// Function to prompt for masked input
function promptPassword(query) {
return new Promise((resolve) => {
// Create a hidden readline instance to control input/output
const stdin = process.stdin;
// Save the original configuration
const originalStdinIsTTY = stdin.isTTY;
if (originalStdinIsTTY) {
stdin.setRawMode(true);
}
let password = '';
// Write the query
process.stdout.write(query);
// Handle keypress events
const onData = (key) => {
// Ctrl+C
if (key.toString() === '\u0003') {
process.stdout.write('\n');
process.exit();
}
// Enter key
if (key.toString() === '\r' || key.toString() === '\n') {
if (originalStdinIsTTY) {
stdin.setRawMode(false);
}
stdin.removeListener('data', onData);
process.stdout.write('\n');
resolve(password);
return;
}
// Backspace
if (key.toString() === '\u0008' || key.toString() === '\u007f') {
if (password.length > 0) {
password = password.slice(0, -1);
process.stdout.write('\b \b'); // Erase last character
}
return;
}
// Regular character
password += key.toString();
process.stdout.write('*'); // Show asterisk for each character
};
stdin.on('data', onData);
});
}
// Example usage
async function login() {
const username = await new Promise((resolve) => {
rl.question('Username: ', (answer) => {
resolve(answer);
});
});
const password = await promptPassword('Password: ');
console.log(`\nAttempting login for user: ${username}`);
// Simulate authentication check
if (username === 'admin' && password === 'password') {
console.log('Login successful!');
} else {
console.log('Invalid username or password');
}
rl.close();
}
// Start the login process
login();